from json.tool import main
import numpy as np

def gussian_Mask(pixels, dec=2):
    rou2 = pixels*pixels
    part1 = 1/(2*np.pi*rou2)
    g00 = part1*np.exp(-(0+0)/(2*rou2))
    g01 = part1*np.exp(-(0+1)/(2*rou2))
    g11 = part1*np.exp(-(1+1)/(2*rou2))

    g00 = round(g00, dec)
    g01 = round(g01, dec)
    g11 = round(g11, dec)

    mask = np.array([
        [g11, g01, g11],
        [g01, g00, g01],
        [g11, g01, g11]
    ])
    return mask

def zero_Pad(x, pad_height, pad_width):# 先在待处理矩阵周围填充0

    H, W = x.shape# H为待处理矩阵的高（行），Wi为待处理矩阵的宽（列）
    out = None
    out = np.zeros((H+2*pad_height, W+2*pad_width))# 知道尺寸后先全填入0
    out[pad_height:pad_height+H, pad_width:pad_width+W] = x# 后在中间填入x，这样边缘填充0就完成了
    return out


def conv_Fast(x, h, dec=2):

    Hi, Wi = x.shape# Hi为待处理矩阵的高（行），Wi为待处理矩阵的宽（列）
    Hh, Wh = h.shape# Hh为卷积核的高（行），Wi为卷积的宽（列）
    out = np.zeros((Hi, Wi))# 相当于占位

    pad_height = Hh // 2   #mode为same情况下，填充0的数量取决于卷积核h的尺寸
    pad_width = Wh // 2
    image_padding = zero_Pad(x, pad_height, pad_width)
    h_flip = np.flip(np.flip(h, 0), 1) #np.flip 是翻转函数,参数0为上下翻转也就是行翻转,而参数1为左右翻转也就是列翻转

    for i in range(Hi):
        for j in range(Wi):
            out[i][j] = np.sum(np.multiply(h_flip, image_padding[i:(i+Hh), j:(j+Wh)]))# 加权求和后写入结果到out对应位置
            out[i][j] = round(out[i][j], dec)
    return out

h = np.array([
        [-0.125, -0.125, -0.125],
        [-0.125, 1.000, -0.125],
        [-0.125, -0.125, -0.125]
    ])

# h = np.array([
#         [-1, -1, -1],
#         [-1, 8, -1],
#         [-1, -1, -1]
#     ])

pix = 0.52

# pix = 0.50
dec = 2

print(conv_Fast(gussian_Mask(pix, dec), h))
